<?php
include_once 'include.inc';
$db = new DB();

function updateVarBuffer($name, $value) {
	global $db;
	$query="update var_buffer set `value`='$value' where name='$name'";
	mysql_query($query);
}

function getVarBuffer($name) {
	global $db;
	$query="select `value` from var_buffer where name='$name'";
	$res = mysql_query($query);
	if ($arr = mysql_fetch_array($res, MYSQL_ASSOC))
		return $arr['value'];
	return '';
}
function registerVarBuffer($name) {
	global $db;
	mysql_query("insert into var_buffer values('$name', '')");
	mysql_query("update var_buffer set `value`='' where name='$name'");
	$res = mysql_query("SELECT count( * ) AS cnt FROM var_buffer WHERE name='$name'");
	if ($arr = mysql_fetch_array($res, MYSQL_ASSOC))
		if ($arr['cnt'] > 0) {
			return true;
		}

	return false;
}

function registerVarBufferArray($array) {
	foreach ($array as $value) {
		registerVarBuffer($value);
	}
}

//error($error_name, $note, $log_name);
function error($error, $note, $log_name = 'no_name') {
	global $db;
	$date = date('Y-m-d H:i:s');
	$params = array('error_name' => $error, 'note' => $note, 'log_name'=>$log_name, 'date'=>$date);
	$db->insert('system_error_log', $params);
	//var_dump($params);
	
}

//THREADS TEST PART
function doUpdate(){
	$access = tryDBLock();

	if ($access === true) {
		$t1 = time();
		//$cnt=update();
		$update['cnt']=update();
		$t2 = time();
		$update['time']=$t2-$t1;
		DBUnlock();
		return $update;
	}
	else $answer=updateProcess();
	return $answer;
}
function DBUnlock() {
	mysql_query("update log.lock set value='UNLOCK';");
}
function updateProcess(){
	$answer= "Permission denied. Its updating already";
	return $answer;
}

function tryDBLock() {
	$access = false;
	mysql_query('lock tables log.lock write;');
	if (getLockVal() === 'UNLOCK') {
		mysql_query("update log.lock SET value = 'LOCK';");
		if (getLockVal() === 'LOCK') {
			$access = true;
		}
	}
	mysql_query('unlock tables;');
	return $access;
}

function getLockVal() {
	$res = mysql_query('select SQL_NO_CACHE value from log.lock;');
	$ret = mysql_result($res, 0, 0);
	return  $ret;
}

//END OF TEST THREADS

function update() {

	set_time_limit(0);
	
	//register names in var_buffer
	$array=array('proxy_all','proxy_done', 'radius_all', 'radius_done', 'tacacs_all', 'tacacs_done', 'fail_all', 'fail_done', 'pass_all', 'pass_done');
	registerVarBufferArray($array);
	
	global $db;
	$files = scandir('log/');
	$path = 'log';
	$cnt = array();

	//init
	
	$ff = new ProxyFileFilter($files);
	$proxyFiles=$ff->getFiles();
	$proxyFileLogReader = new FileLogReader($proxyFiles, $path);
	$proxyFileLogReader->addListener(new FileUpdateListener('proxy'));
	$proxyParser = new ProxyLogParser($proxyFileLogReader);
	
	
	$ff = new RadiusFileFilter($files);
	$radiusFiles=$ff->getFiles();
	$radiusFileLogReader = new FileLogReader($radiusFiles, $path);
	$radiusFileLogReader->addListener(new FileUpdateListener('radius'));
	$radiusParser = new RadiusLogParser($radiusFileLogReader);
	
	
	$ff = new TacacsFileFilter($files);
	$tacacsFiles=$ff->getFiles();
	$tacacsFileLogReader = new FileLogReader($tacacsFiles, $path);
	$tacacsFileLogReader->addListener(new FileUpdateListener('tacacs'));
	$tacacsParser = new TacacsLogParser($tacacsFileLogReader);
	
	
	$ff = new FailedAttemptsFileFilter($files);
	$failedFiles=$ff->getFiles();
	$failedFileLogReader = new FileLogReader($failedFiles, $path);
	$failedFileLogReader->addListener(new FileUpdateListener('fail'));
	$failedParser = new FailedAttemptsLogParser($failedFileLogReader);
	
	$ff = new PassedAuthenticationsFileFilter($files);
	$passedFiles=$ff->getFiles();
	$passedFileLogReader = new FileLogReader($passedFiles, $path);
	$passedFileLogReader->addListener(new FileUpdateListener('pass'));
	$passedParser = new PassedAuthenticationsLogParser($passedFileLogReader);
	//init
	
	$i = 0;
	while ($log = $proxyParser->parse()){
		if (true === $log['error']) {
			continue;
		}
		$db_log = $proxyParser->getDBVersion($log);
		$db->insert('proxy_log', $db_log);
		$i++;
	}
	
	$cnt['proxy']=$i;
	//RemoveToArchiveProxy($proxyFiles);


	$i = 0;
	while ($log = $radiusParser->parse()) {
	
		if (true === $log['error']) {
			continue;
		}
		$db_log = $radiusParser->getDBVersion($log);
		$db->insert('radius_log', $db_log);
		$i++;
	}
	$cnt['radius']=$i;
	RemoveToArchive($radiusFiles);


	$i = 0;
	while ($log = $tacacsParser->parse()) {
		if (true === $log['error']) {
			continue;
		}
		$db_log = $tacacsParser->getDBVersion($log);
		$db->insert('tacacs_log', $db_log);
		$i++;
	}
	$cnt['tacacs']=$i;
	RemoveToArchive($tacacsFiles);

	
	$i = 0;
	while ($log = $failedParser->parse()) {

		if (true === $log['error']) {
			continue;
		}
		$db_log = $failedParser->getDBVersion($log);
		$db->insert('failed_attempts_log', $db_log);
		$i++;
	}
	$cnt['failed']=$i;
	//RemoveToArchive($failedFiles);


	
	$i = 0;
	while ($log = $passedParser->parse()) {
		if (true === $log['error']) {
			continue;
		}
		$db_log = $passedParser->getDBVersion($log);
		$db->insert('passed_authentications_log', $db_log);
		$i++;
	}
	$cnt['passed']=$i;
	RemoveToArchive($passedFiles);

	return $cnt;
}


function RemoveToArchiveProxy($file){
	global $Registry;
	$date=date("Y-m-d_h-i-s");
	$pattern = '/(?P<access>[access]+)(?P<fileformat>\.log[.\d]*)/';
	$matches = null;
	foreach ($file as $f) {
		preg_match($pattern, $f, $matches);
		$newfile=$matches['access'];
		$fileformat=$matches['fileformat'];
		$oldname= $Registry['inputFileDir'].'/'.$f;
		$newname= $Registry['archive'].'/'.$newfile.'_'.$date.$fileformat;
		rename($oldname, $newname);
	}
}

function RemoveToArchive($file){
	global $Registry;
	$date=date("Y-m-d_h-i-s");
	$pattern = '/(?P<filename>[\w \-\+]*)(?P<fileformat>\.\w{1,3})/';
	$matches = null;
	foreach ($file as $f) {
		preg_match($pattern, $f, $matches);
		$newfile=$matches['filename'];
		$fileformat=$matches['fileformat'];
		$oldname= $Registry['inputFileDir'].'/'.$f;
		$newname= $Registry['archive'].'/'.$newfile.'_'.$date.$fileformat;
		rename($oldname, $newname);
	}
}

//DELETING TABLE CONTENT
// DELETE table content
function CheckingDate(){
	$today = getdate();
	$month = $today['mon'] - 1;
	$result=DeleteTable($month);
	return $result;
}

function DeleteTable($month) {
	$query= "DELETE FROM proxy_log WHERE MONTH(date)=".$month;
	$result['proxy']=mysql_query($query);

	$query= "DELETE FROM radius_log WHERE MONTH(date)=".$month;
	$result['radius']=mysql_query($query);

	$query= "DELETE FROM tacacs_log WHERE MONTH(date)=".$month;
	$result['tacacs']=mysql_query($query);
	
	$query= "DELETE FROM failed_attempts_log WHERE MONTH(date)=".$month;
	$result['fail']=mysql_query($query);
	
	$query= "DELETE FROM passed_authentications_log WHERE MONTH(date)=".$month;
	$result['pass']=mysql_query($query);

	return $result;
}

function DeleteAll() {
	$query= "TRUNCATE TABLE log.radius_log";
	$result['radius']=mysql_query($query);

	$query= "TRUNCATE TABLE log.tacacs_log";
	$result['tacacs']=mysql_query($query);
	
	$query= "TRUNCATE TABLE log.failed_attempts_log";
	$result['fail']=mysql_query($query);
	
	$query= "TRUNCATE TABLE log.passed_authentications_log";
	$result['pass']=mysql_query($query);
	
	$query= "TRUNCATE TABLE log.proxy_log";
	$result['proxy']=mysql_query($query);
	return $result;
}


//REPORTS part
function VisitedSites() {
	global $db;
	$query="select ip, domain, count(domain) as cnt from `proxy_log` group by domain having count(domain)>0 ORDER BY cnt DESC";
	$report = $db->selectArray($query);
	return $report;
}

function IPTraffic() {
	global $db;
	$query="select ip, sum(content_length) as traffic from `proxy_log` group by ip order by ip ASC";
	$report = $db->selectArray($query);
	return $report;
}

//PROXY FORMS FUNCTIONS
//View
function getIPlist() {
	global $db;
	$query="select ip from `proxy_log` group by ip";
	$list = $db-> selectArray($query);
	return $list;
}

function visitedSites_ip($date_start, $date_end, $ip, $length){
	global $db;
	$query="SELECT ip, domain, count(domain) as cnt FROM `proxy_log` WHERE ip='$ip' AND date BETWEEN '$date_start' AND '$date_end' AND content_length > '$length' GROUP BY domain HAVING count(domain)>0 ORDER BY cnt DESC";

	$result=$db->selectArray($query);
	return $result;
}

function visitedSites_all($date_start, $date_end, $length){
	global $db;
	$query="SELECT ip, domain, count(domain) as cnt FROM `proxy_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND content_length > '$length' GROUP BY domain HAVING count(domain)>0 ORDER BY cnt DESC";

	$result=$db->selectArray($query);
	return $result;
}

function timeVisiting_ip($ip, $domain,$date_start, $date_end, $length){
	global $db;
	$query="SELECT ip, domain, date FROM `proxy_log` WHERE IP='$ip' AND date BETWEEN '$date_start' AND '$date_end' AND content_length > '$length' AND domain LIKE '%$domain%' ORDER BY date DESC";

	$result=$db->selectArray($query);
	return $result;
}

function timeVisiting_all($domain, $date_start, $date_end, $length){
	global $db;
	$query="SELECT ip, domain, date FROM `proxy_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND domain LIKE '%$domain%' AND content_length > '$length' ORDER BY date DESC";

	$result=$db->selectArray($query);
	return $result;
}

function formatSize($size) {
	
	    $units = array(' Б', ' Кб', ' Мб', ' Гб', ' Тб');
	    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
	    return round($size, 2).$units[$i];
}
function trafic_ip($date_start, $date_end, $ip, $length){
	global $db;
	$query="SELECT ip, sum(content_length) as Trafic FROM `proxy_log` WHERE ip='$ip' AND content_length > '$length' AND date BETWEEN '$date_start' AND '$date_end'";
	$result=$db->selectArray($query);
	$result[0]['trafic_format']=formatSize($result[0]['trafic']);
	return $result;
}

function trafic_all($date_start, $date_end, $length){
	global $db;
	$query="SELECT ip, sum(content_length) as trafic FROM `proxy_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND content_length > '$length' GROUP BY ip";
	$result['trafic']=$db->selectArray($query);
	$cnt=count($result['trafic']);
	for ($i=0; $i<$cnt; $i++)
	{
		$result['trafic'][$i]['trafic_format']=formatSize($result['trafic'][$i]['trafic']);
	}
	return $result;
}


//RADIUS FORMS FUNCTIONS
function RadiusRemoteAccessList($date_start, $date_end) {
	global $db;
	
	$query="SELECT radius_log.* FROM log.radius_called_station_id INNER JOIN log.radius_log ON radius_called_station_id.address = radius_log.called_station_id";
	$result=$db->selectArray($query);
	
	return $result;	
	
}

function Radius802List($date_start, $date_end) {
	global $db;
	
		$query="SELECT * FROM `radius_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND groupname LIKE '802.1x%'";
		$result=$db->selectArray($query);
		
	return $result;	
}

function RadiusAdminAccessList($date_start, $date_end) {
	global $db;
	$query="SELECT * FROM `radius_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND nas_port_id LIKE 'tty%'";
		$result=$db->selectArray($query);
	return $result;	
}

//FAILED ATTEMPTS FORMS FUNCTIONS
function FailedNonTelephoneList($date_start, $date_end) {
	global $db;
	$query="SELECT * FROM `failed_attempts_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND username REGEXP \"[^[:digit:]]+\" ";
	$result=$db->selectArray($query);
	return $result;	
}

//PASSED AUTHENTICATIONS FORMS FUNCTIONS
function PassedSoNetList($date_start, $date_end) {
	global $db;
	$query="SELECT * FROM `passed_authentications_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND username REGEXP \"so\\.net\" ";
	$result=$db->selectArray($query);
	//var_dump($result);
	return $result;	
}

function PassedRemoteAccessList($date_start, $date_end) {
	global $db;
	$query="SELECT passed_authentications_log.* FROM log.passed_address INNER JOIN log.passed_authentications_log ON passed_address.address = passed_authentications_log.nas_ip_address";
	$result=$db->selectArray($query);
	return $result;	
}

//TACACS FORMS FUNCTIONS
function TacacsTTYList($date_start, $date_end) {
	global $db;
	global $db;
	$query="SELECT * FROM `tacacs_log` WHERE date BETWEEN '$date_start' AND '$date_end' AND nas_portname LIKE 'tty%'";
	$result=$db->selectArray($query);
	return $result;	
}

function TacacsCustomList($date_start, $date_end) {
	global $db;
	$query="SELECT tacacs_log.* FROM log.tacacs_nas_ip INNER JOIN log.tacacs_log ON tacacs_nas_ip.address = tacacs_log.nas_ip_address";
	$result=$db->selectArray($query);
	return $result;	
}

?>